package streams;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class DataStreamDemo {
 
    public static void main(String[] args) {
        // Prepares some data to be written to a file.
        int cityIdA = 1;
        String cityNameA = "Piura";
        int cityPopulationA = 500000;
        float cityTempA = 15.50f;
        
        try {
            // Create an instance of FileOutputStream with cities.dat
            FileOutputStream fos = new FileOutputStream("cities.dat");
            DataOutputStream dos = new DataOutputStream(fos);
 
            // DataOutputStream class have various method that allow
            // us to write primitive type data and string. There are
            // method called writeInt(), writeFloat(), writeUTF(),
            // etc.
            dos.writeInt(cityIdA);
            dos.writeUTF(cityNameA);
            dos.writeInt(cityPopulationA);
            dos.writeFloat(cityTempA);
            
            dos.flush();
            dos.close();
 
            // DataInputStream class have the corresponding
            // read methods to read data from the file. Some of
            // the method names are readInt(), readFloat(),
            // readUTF(), etc.
            FileInputStream fis = new FileInputStream("cities.dat");
            DataInputStream dis = new DataInputStream(fis);
 
            // Read the data
            int cityId1 = dis.readInt();
            System.out.println("Id: " + cityId1);
            String cityName1 = dis.readUTF();
            System.out.println("Name: " + cityName1);
            int cityPopulation1 = dis.readInt();
            System.out.println("Population: " + cityPopulation1);
            float cityTemperature1 = dis.readFloat();
            System.out.println("Temperature: " + cityTemperature1);
 
            dis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}